package wangjg.sso;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Date;

import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;
import net.sf.json.util.JSONUtils;

import wangjg.sso.util.*;

public class ParameterLogin {
	private static char separator = ';';
	private String salt = ":><M#$%^&*HGJ3yh6";
	private Class userClass;
	// userinfo;className,date;code
	private static String reg = "{salt:\"aaa\",username:'wjg'};wangjg.sso.ParameterLogin;"+Long.MAX_VALUE+";WERTYUIFGHJERTYWERTYUIFGHJERTY";

	public static void main(String args[]) throws Exception {
		ParameterLogin pl=new ParameterLogin();
		pl.setUserClass(ParameterLogin.class);
		String json=pl.makeParameter(pl);
		System.out.println("json=="+json);
//		ParameterLogin obj=(ParameterLogin) pl.login(json);
//		System.out.println(obj);
		System.out.println("============");
		pl=new ParameterLogin();
		String userInfo="{id:33,username=\"kf1\",email=\"\",nickname=\"小王\"}";
		String parameters=pl.makeParameter(userInfo);
		System.out.println("parameters="+parameters);
		System.out.println(pl.login(parameters));
		
		System.out.println(md5("{id:33,username=\"kf1\",email=\"\",nickname=\"小王\"};wangjg.kefu.entity.Operator;1282834126970"+pl.getSalt()));
		String s="{id:33,username=\"kf1\",email=\"\",nickname=\"小王\"};wangjg.kefu.entity.Operator;1282835216351:><M#$%^&*HGJ3yh6";
		System.out.println(s.getBytes("utf-8").length);
		System.out.println(s.getBytes("gbk").length);
	}

	public ParameterLogin(){
		initJson();
	}
	
	public String makeParameter(Object user) {
		String userInfo="";
		if(user instanceof String){
			userInfo = (String) user;
		}else{
			JSONObject jsonObject = JSONObject.fromObject(user,jsonConfig4writing);
			userInfo = jsonObject.toString();
		}
		String time = "" + System.currentTimeMillis();
		String className = this.userClass!=null?this.userClass.getName():user.getClass().getName();
		String temp = userInfo + separator + className + separator + time + salt;
		String md5Str = md5(temp);
		String str = userInfo + separator + className + separator + time + separator + md5Str;
		try {
			str = new String(Base64.encode(str.getBytes("utf-8")));
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
			return null;
		}
		return str;
	}
	
	private MyDateJsonBeanProcessor djbp = new MyDateJsonBeanProcessor(false);
	private MyDateMorpher dm = new MyDateMorpher();
	private JsonConfig jsonConfig4writing = new JsonConfig();
	
	private void initJson(){
        jsonConfig4writing.registerJsonBeanProcessor(Date.class,djbp);
        JSONUtils.getMorpherRegistry().registerMorpher(dm);
	}
	public Object login(String parameters) {
		try {
			byte[] bytes = Base64.decode(parameters);
			parameters = new String(bytes,"utf-8");
			int pos3 = parameters.lastIndexOf(separator);
			int pos2 = parameters.lastIndexOf(separator, pos3 - 1);
			int pos1 = parameters.lastIndexOf(separator, pos2 - 1);
			if (pos3==-1 || pos2==-1 || pos1==-1)
				return null;
			String userInfo = parameters.substring(0, pos1);
			String className = parameters.substring(pos1+1, pos2);
			String time = parameters.substring(pos2 + 1, pos3);
			String md5Str = parameters.substring(pos3 + 1);

			if (System.currentTimeMillis()-Long.parseLong(time) > 1000 * 60000) {
				return null;
			}

			String temp = userInfo + separator + className + separator + time + salt;
			String md5str2 = md5(temp);
			if (!(md5str2).equals(md5Str)) {
				return null;
			}
			Class cls = this.userClass!=null?this.userClass:Class.forName(className);
			JSONObject jsonObject = JSONObject.fromObject(userInfo);
			JsonConfig jsonConfig = new JsonConfig();
			jsonConfig.setRootClass(cls);
			Object user = JSONObject.toBean(jsonObject,jsonConfig);
			return user;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	public Object logout() throws IOException {
		return null;
	}

	private static String md5(String piStr) {
		String encodeStr = "";
		byte[] digesta = null;
		try {
			java.security.MessageDigest alg = java.security.MessageDigest
					.getInstance("MD5");
			alg.update(piStr.getBytes("utf-8"));
			digesta = alg.digest();
			encodeStr = byte2hex(digesta);
		} catch (Exception e) {
		}
		return encodeStr;
	}

	private static String byte2hex(byte[] piByte) {
		String reStr = "";
		String tmpStr = "";
		for (int i = 0; i < piByte.length; i++) {
			int v = piByte[i] & 0xFF;
			if (v < 16)
				reStr += "0";
			reStr += Integer.toString(v, 16).toLowerCase();
		}
		return reStr;
	}

	public void setSalt(String salt) {
		this.salt = salt;
	}

	public void setUserClass(Class userClass) {
		this.userClass = userClass;
	}

	public String getSalt() {
		return salt;
	}
}
